//
//  DetailViewController.m
//  Product_NEWS
//
//  Created by dllo on 16/1/4.
//  Copyright © 2016年 FCH. All rights reserved.
//

#import "DetailViewController.h"
#import "VideoDetailTableViewCell.h"
#import <AVFoundation/AVFoundation.h>
#import "AppTools.h"
#import "VideoDetailModel.h"
@interface DetailViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, retain) AVPlayerItem *playerItem;
@property (nonatomic, retain) AVPlayer *player;
@property (nonatomic, retain) AVPlayerLayer *playerLayer;
@property (nonatomic, retain) UIView *bottemView;
@property (nonatomic, retain) UIView *playView;
@property (nonatomic, retain) UISlider *progressSlider;
@property (nonatomic, assign) CGFloat totalDuration;
@property (nonatomic, assign) BOOL isPlaying;
@property (nonatomic, retain) UIButton *playButton;
@property (nonatomic, retain) UILabel *leftTimeLabel;
@property (nonatomic, retain) UILabel *rightTimeLabel;
@property (nonatomic, retain) UILabel *titleLabel;
@property (nonatomic, retain) UITableView *replayTableView;
@property (nonatomic, retain) NSMutableArray *replayArray;
@property(nonatomic, retain)VideoDetailModel *Vmodel;
@end

@implementation DetailViewController
- (void)dealloc{
    [_playButton release];
    [_player release];
    [_playerItem release];
    [_playerLayer release];
    [_playView release];
    [_bottemView release];
    [_titleLabel release];
    [_model release];
    [_replayArray release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
 
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationItem.title = self.model.title;
    self.navigationController.navigationBar.barTintColor = [UIColor whiteColor];
    
  
    
    self.replayTableView = [[UITableView alloc] initWithFrame:CGRectMake(10, 270*SCREEN_HEIGHT, self.view.frame.size.width,   667 *SCREEN_HEIGHT - 260*SCREEN_HEIGHT)];
    self.replayTableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.replayTableView];
    [_replayTableView release];
    
    self.replayTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    
    
    [self.replayTableView registerClass:[VideoDetailTableViewCell class] forCellReuseIdentifier:@"replayCell"];
    
    self.replayTableView.delegate = self;
    self.replayTableView.dataSource = self;
    
    self.replayArray = [NSMutableArray array];
    
    
    UIImage *image = [UIImage imageNamed:@"icon_back@2x"];
    image = [image imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
   
    
    NSURL *url = [NSURL URLWithString:self.model.mp4_url];
    
    self.playerItem = [AVPlayerItem playerItemWithURL:url];
    
    self.player = [AVPlayer playerWithPlayerItem:self.playerItem];
    
    self.playerLayer = [AVPlayerLayer playerLayerWithPlayer:self.player];
    
    self.playerLayer.videoGravity = AVLayerVideoGravityResizeAspectFill;
    self.playerLayer.frame = CGRectMake(20 * SCREEN_WIDTH, 50* SCREEN_HEIGHT, 375 *SCREEN_WIDTH - 40* SCREEN_WIDTH , 200* SCREEN_HEIGHT);
    
    
    self.playView = [[UIView alloc] initWithFrame:CGRectMake(0, 44* SCREEN_HEIGHT, 375 * SCREEN_WIDTH, 260 * SCREEN_HEIGHT)];
    self.playView.backgroundColor = [UIColor blackColor];
    [self.view addSubview:self.playView];
    [self.playView.layer addSublayer:self.playerLayer];
    [_playView release];
    self.playView.userInteractionEnabled = YES;
    
    self.bottemView = [[UIView alloc] initWithFrame:CGRectMake(20 * SCREEN_WIDTH, 20* SCREEN_HEIGHT + 210* SCREEN_HEIGHT,  375 *SCREEN_WIDTH - 40* SCREEN_WIDTH, 25* SCREEN_HEIGHT)];
    self.bottemView.backgroundColor = [UIColor blackColor];
    self.bottemView.alpha = 0.5;
    [self.playView addSubview:self.bottemView];
    [_bottemView release];
    
    self.bottemView.userInteractionEnabled = YES;
    
    
    self.playButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.playButton.frame = CGRectMake(5* SCREEN_WIDTH, 5 * SCREEN_HEIGHT, 20* SCREEN_WIDTH, 20* SCREEN_HEIGHT);
    [self.playButton setImage:[UIImage imageNamed:@"iconfont-bofangqibofang.png"] forState:UIControlStateNormal];
    //    [playButton setTitle:@"播放" forState:UIControlStateNormal];
    [self.playButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.bottemView addSubview:self.playButton];
    [_playButton addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    // title
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(30* SCREEN_WIDTH, 20 * SCREEN_HEIGHT, 300* SCREEN_WIDTH, 30* SCREEN_HEIGHT)];
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.text = self.model.title;
    self.titleLabel.font = [UIFont systemFontOfSize:15 * SCREEN_WIDTH];
    [self.playView addSubview:self.titleLabel];
    
    
    self.progressSlider = [[UISlider alloc] initWithFrame:CGRectMake(90 * SCREEN_WIDTH, 5* SCREEN_HEIGHT, 200* SCREEN_WIDTH, 20* SCREEN_HEIGHT)];
    self.progressSlider.value = 0;
    self.progressSlider.maximumValue = 1;
    self.progressSlider.minimumValue = 0;
    
    
    self.leftTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(40* SCREEN_WIDTH, -10 * SCREEN_HEIGHT, 50* SCREEN_WIDTH, 50* SCREEN_HEIGHT)];
    self.leftTimeLabel.font = [UIFont systemFontOfSize:13 * SCREEN_WIDTH];
    self.leftTimeLabel.textColor = [UIColor whiteColor];
    self.leftTimeLabel.text = @"00:00";
    [self.bottemView addSubview:self.leftTimeLabel];
    
    
    self.rightTimeLabel = [[UILabel alloc] initWithFrame:CGRectMake(300*SCREEN_WIDTH, -10* SCREEN_HEIGHT, 50 * SCREEN_WIDTH, 50* SCREEN_HEIGHT)];
    self.rightTimeLabel.textColor = [UIColor whiteColor];
    self.rightTimeLabel.text = @"00:00";
    self.rightTimeLabel.font = [UIFont systemFontOfSize:13*SCREEN_WIDTH];
    [self.bottemView addSubview:self.rightTimeLabel];
    
    
    
    [self.bottemView addSubview:self.progressSlider];
    [self.progressSlider addTarget:self action:@selector(sliderAction:) forControlEvents:UIControlEventValueChanged];
    [_progressSlider release];
    
    [self showPlayerProgress];
    
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
    
    [self.playView addGestureRecognizer:tap];
    
    
    [self getData];
    
    
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}




- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 60 * SCREEN_HEIGHT  + [VideoDetailTableViewCell heightForText:self.Vmodel.b width:315 * SCREEN_WIDTH];
        
    
}



- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.replayArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    VideoDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"replayCell"];
    self.Vmodel = [self.replayArray objectAtIndex:indexPath.row];
    cell.model = self.Vmodel;
    
    return cell;
}

- (void)viewDidDisappear:(BOOL)animated{
    if (self.isPlaying == YES) {
        [self.player pause];
        [self.playView removeFromSuperview];
    }
}


- (void)buttonAction:(UIButton *)button{
    
    if (self.isPlaying == NO) {
        [self.player play];
        [self.playButton setImage:[UIImage imageNamed:@"iconfont-zanting.png"] forState:UIControlStateNormal];
        
    }else{
        
        [self.player pause];
        [self.playButton setImage:[UIImage imageNamed:@"iconfont-bofangqibofang.png"] forState:UIControlStateNormal];
    }
    self.isPlaying = !self.isPlaying;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [UIView animateWithDuration:2 animations:^{
                
                self.bottemView.alpha = 0;
            }];
            
        });
        
    });
    
}



- (void)sliderAction:(UISlider *)slider{
    
    
    double currentTime = slider.value * self.totalDuration;
    
    CMTime time = CMTimeMake(currentTime, 1);
    
    [self.player seekToTime:time completionHandler:^(BOOL finished) {
        
        [self.player play];
        
    }];
    
    
}


- (void)showPlayerProgress{
    
    
    CMTime time = CMTimeMake(1, 1);
    
    __block DetailViewController *playVC = self;
    
    [playVC.player addPeriodicTimeObserverForInterval:time queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        
        CMTime currentTime = playVC.playerItem.currentTime;
        
        CMTime totalTime = playVC.playerItem.duration;
        
        double currentT = CMTimeGetSeconds(currentTime);
        double totalT = CMTimeGetSeconds(totalTime);
        
        playVC.progressSlider.value = currentT / totalT;
        
        playVC.totalDuration = totalT;
        
      
        
        // 总时长
        CGFloat duration = CMTimeGetSeconds(self.playerItem.duration);
        // 当前时长
        CGFloat current = CMTimeGetSeconds(self.player.currentTime);
        
        //倒计时
        CGFloat rem = duration - current;
        
        NSString *totalTime1 = [NSString stringWithFormat:@"%02d:%02d", (int)rem / 60, (int) rem % 60];
        NSString *currentTime1 = [NSString stringWithFormat:@"%02d:%02d", (int) current / 60, (int) current % 60];
        
        self.leftTimeLabel.text = currentTime1;
        self.rightTimeLabel.text = totalTime1;
        
    }];
    
    
}


- (void)tapAction:(UITapGestureRecognizer *)tap{
    
    
    if (self.bottemView.alpha == 0) {
        [UIView animateWithDuration:1 animations:^{
            
            self.bottemView.alpha = 1;
        }];
    }else{
        [UIView animateWithDuration:1 animations:^{
            
            self.bottemView.alpha = 0;
        }];
    }
    
}


- (void)getData{
    NSString *url =  [NSString stringWithFormat:@"http://comment.api.163.com/api/json/post/list/new/normal/video_bbs/%@/desc/0/10/10/2/2", self.model.replyid];
    
    [AppTools getDataWithAFNUrl:url block:^(id result) {
        NSMutableDictionary *dic = result;
        NSMutableArray *array = [dic objectForKey:@"newPosts"];
        for (NSMutableDictionary *dict in array) {
            NSMutableDictionary *dic1 = [dict objectForKey:@"1"];
            VideoDetailModel *replayModel = [[VideoDetailModel alloc] init];
            [replayModel setValuesForKeysWithDictionary:dic1];
            
            
            [self.replayArray addObject:replayModel];
            
        }
        [self.replayTableView reloadData];
        
    } errorBlock:^(NSError *error) {
        
        
    }];
    
}

    
    
    
    
    
    
    
    
    
    




@end
